package com.spark.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus配置类
 *
 * @author LYCHEE
 * @date 2024/12/11 11:47
 */
@Configuration
@MapperScan(value={"com.spark.**.mapper"})
public class MybatisPlusConfig {

    /**
     * 加载插件
     *  如果配置多个插件, 切记分页最后添加
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 阻断插件
        interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 配置雪花算法生成器
     * 默认实现：DefaultIdentifierGenerator
     */
    @Bean
    public IdentifierGenerator idGenerator() {
        return new CustomIdGenerator();
    }

    /**
     * 自定义生成器（可选，用于扩展默认行为）
     */
    static class CustomIdGenerator implements IdentifierGenerator {
        private final DefaultIdentifierGenerator defaultGenerator = new DefaultIdentifierGenerator();
        @Override
        public Long nextId(Object entity) {
            // 直接调用默认实现
            return defaultGenerator.nextId(entity);
        }

        @Override
        public String nextUUID(Object entity) {
            // 不需要UUID生成则留空
            return null;
        }
    }

    /**
     * 如果是对全表的删除或更新操作，就会终止该操作
     *  https://baomidou.com/plugins/block-attack/
     */
    public BlockAttackInnerInterceptor blockAttackInnerInterceptor(){
        return new BlockAttackInnerInterceptor();
    }

}
